package com.jm.weibo.ui;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jm.weibo.logic.IWeiboActivity;
import com.jm.weibo.logic.ImageFaceAdapter;
import com.jm.weibo.logic.MainService;
import com.jm.weibo.logic.Task;
import com.jm.weibo.util.GPSPoint;
import com.jm.weibo.util.MyToastUtil;

public class NewWeiboActivity extends Activity implements IWeiboActivity{
	
	// 发送微博的结果
    public static final int REF_NEW_WEIBO_RESULT = 1;

	private EditText etNewBlog;
    
    private GridView gridView;
    
    public boolean hasPic=false;
    
    public boolean hasGPS=false;
    
    public boolean isFace = false;
    
    public byte dat[];//图片数据
    
    public double gps[];//经纬度数据 
	 
    private RelativeLayout facesLayout;
    
	//得到顶部的按钮设定返回和发表
	private View titleview;
	
	private TextView tvTextLimit;
	
	//添加图片按钮 
	private ImageButton btaddPic;
	//返回
	private Button btnBack ;
	
	 //发表  
	private Button btRefbolg;
    
    //添加经纬度
	private ImageButton btaddGPS;
    
	//添加表情
	private ImageButton btnFaces ;

    //插入话题
	private ImageButton ibInsertTopic;
    
    //插入用户名
	private ImageButton ibInsertAt;
    
	//发布微博进度条
	private View progress4NewProgress;
	
	protected void onCreate(Bundle savedInstanceState) {
		 
		super.onCreate(savedInstanceState);
		//取消标题栏
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		this.setContentView(R.layout.newblog);

		this.initControlsAndAddControlsEvent();
		
		//
		MainService.mainService.allActivity.add(this);
	}
	
	/**
	 * 初始化控件和为控件添加事件
	 */
	private void initControlsAndAddControlsEvent() {
		//得到输入文字的文本框
		this.etNewBlog = (EditText)this.findViewById(R.id.etNewBlog);
		this.titleview = this.findViewById(R.id.title);
		this.tvTextLimit  = (TextView) this.findViewById(R.id.tvTextLimit);
		this.btnBack = (Button)titleview.findViewById(R.id.title_bt_left);
		 //发表  
		this.btRefbolg=(Button)titleview.findViewById(R.id.title_bt_right);
		this.btRefbolg.setText("发表");
	    //进度条视图 
		this.progress4NewProgress = this.findViewById(R.id.progress4NewProgress);
		this.progress4NewProgress.setVisibility(View.GONE);
		//添加发表事件
	    this.btRefbolg.setOnClickListener(new OnClickListener(){     
			
	    	public void onClick(View arg0) {
			     
	    		   
//				  NewWeiboActivity.this.progress4NewProgress.setVisibility(View.VISIBLE);
	    	      HashMap hm=new HashMap();
		    	  hm.put("msg", etNewBlog.getText().toString());
		    	  
		    	  if(hasGPS){
		    		  hm.put("gpspoint", gps);
				      Task ts=new Task(Task.TASK_NEW_WEIBO_GPS,hm);
				      MainService.addNewTask(ts);  
		    	  }
		    	  else if(hasPic){
			    	  hm.put("picdat", dat);
				      Task ts=new Task(Task.TASK_NEW_WEIBO_PIC,hm);
				      MainService.addNewTask(ts);
		    	  }else{
		    		  if(etNewBlog.getText().toString() == null || etNewBlog.getText().toString().length() == 0){
		    			  MyToastUtil.myToastShow(NewWeiboActivity.this, "您还是写点什么吧");
		    		      return;
		    		  }
		    		  //显示发送微博进度条
		    		  MyToastUtil.myToastShow(NewWeiboActivity.this);
		    		  Task ts=new Task(Task.TASK_NEW_WEIBO,hm);
				      MainService.addNewTask(ts);  
		    	  }
			}
	    });
		
		this.btnBack.setBackgroundResource(R.drawable.title_back);
		this.btnBack.setText("返回");
		//添加图片按钮
	    this.btaddPic=(ImageButton)this.findViewById(R.id.ibInsertPic);
	    //添加进度纬度按钮
	    this.btaddGPS=(ImageButton)this.findViewById(R.id.ibInsertLocation);
	    //添加表情按钮
	    this.btnFaces = (ImageButton) this.findViewById(R.id.ibInsertFace);
	    //添加话题
	    this.ibInsertTopic = (ImageButton) this.findViewById(R.id.ibInsertTopic);
	    //插入用户名
        this.ibInsertAt = (ImageButton) this.findViewById(R.id.ibInsertAt);
          
	    //显示表情的GridView
        this.gridView = (GridView) NewWeiboActivity.this.findViewById(R.id.gridView);   
        this.gridView.setAdapter(new ImageFaceAdapter(NewWeiboActivity.this));
        
        //网状的事件监听
        this.gridView.setOnItemClickListener(new OnItemClickListener() {
 			public void onItemClick(AdapterView<?> parent, View v, int position, long id){
 				Toast.makeText(NewWeiboActivity.this, "你选择了" + (position + 1) + " 号图片", Toast.LENGTH_SHORT).show();
 			    ////需要处理的文本，[faces]是需要被替代的文本   
 				SpannableString spannableString = new SpannableString(etNewBlog.getText().toString() + "[大哥]");
 			    Drawable drawable = NewWeiboActivity.this.getResources().getDrawable(R.drawable.face1 + position);
 			    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
 			    
 			    //添加图片主要用SpannableString和ImageSpan类
 			    
 			    ////要让图片替代指定的文字就要用ImageSpan
 			    ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
 			    //开始替换，注意第2和第3个参数表示从哪里开始替换到哪里替换结束（start和end） 
 			    //最后一个参数类似数学中的集合,[5,12)表示从5到12，包括5但不包括12  
 			    spannableString.setSpan(span, 
 			    		etNewBlog.getText().length(),
 			    		etNewBlog.getText().length()+"[大哥]".length(), 
 			 		    Spannable.SPAN_INCLUSIVE_EXCLUSIVE
 			 		   );  
 			    NewWeiboActivity.this.etNewBlog.setText(spannableString);
// 			    NewWeiboActivity.this.etNewBlog.setC
 			   // Selection.setSelection(etNewBlog, etNewBlog.length()-1); 
 			    etNewBlog.setSelection(etNewBlog.length()-1, etNewBlog.length());
 			}
 		});
        
		//添加返回事件
		this.btnBack.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
		 	    	   finish();
			       }
			    });
		    
		//为etNewBlog添加监听事件
		this.etNewBlog.setOnEditorActionListener(new OnEditorActionListener(){
		 

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				int blogLength = NewWeiboActivity.this.etNewBlog.getText().toString().length();
				if(blogLength <= 140){
					tvTextLimit.setText(String.valueOf(140 - blogLength));
				}else{
					Toast.makeText(NewWeiboActivity.this, "不要太贪心了,超过了长度限制", Toast.LENGTH_SHORT).show();
				}
				System.out.println("=+++++++++++++++++++++");
				return false;
			}
		});
		
	    //拍照
		this.btaddPic.setOnClickListener(new OnClickListener(){
             
			public void onClick(View v) {
					Toast.makeText(NewWeiboActivity.this, "调用系统的拍照程序", Toast.LENGTH_SHORT).show();
					//调用系统的拍照程序，
	        		Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
	     			startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
	            }
	        });
	    
		//添加进度纬度按钮的事件
		this.btaddGPS.setOnClickListener(new OnClickListener(){
	             
				public void onClick(View v) {
					Toast.makeText(NewWeiboActivity.this, "选择经纬度", Toast.LENGTH_SHORT).show();
	        	 	hasGPS = true;
	        	 	ProgressBar pgLoadlocation = (ProgressBar) NewWeiboActivity.this.findViewById(R.id.pgLoadlocation);
	        	 	try {
	        	 		pgLoadlocation.setVisibility(View.VISIBLE);
		        	 	gps= GPSPoint.getGPSPoint(NewWeiboActivity.this);
		        	 	ImageView ivLocation = (ImageView) NewWeiboActivity.this.findViewById(R.id.ivLocation);
		        	 	ivLocation.setVisibility(View.VISIBLE);
					} catch (Exception e) {
						Toast.makeText(NewWeiboActivity.this, "加载进度纬度失败,请重试", Toast.LENGTH_SHORT).show();
					}
	        	 	pgLoadlocation.setVisibility(View.GONE);
	            }
	        });
		//添加表情
		this.btnFaces.setOnClickListener(new OnClickListener(){
	           
				public void onClick(View v) {
					//Toast.makeText(NewWeiboActivity.this, "选择表情", Toast.LENGTH_SHORT).show();
					NewWeiboActivity.this.isFace = !NewWeiboActivity.this.isFace;
					if(NewWeiboActivity.this.facesLayout == null){
						NewWeiboActivity.this.facesLayout = (RelativeLayout) NewWeiboActivity.this.findViewById(R.id.facesLayout);
					}
				 
					if(NewWeiboActivity.this.isFace){
						NewWeiboActivity.this.facesLayout.setVisibility(View.VISIBLE);
						NewWeiboActivity.this.gridView.setVisibility(View.VISIBLE);
					}else{
						NewWeiboActivity.this.facesLayout.setVisibility(View.GONE);
						NewWeiboActivity.this.gridView.setVisibility(View.GONE);
					}
				}
	       }); 
		
		//添加话题
        this.ibInsertTopic.setOnClickListener(new ImageButton.OnClickListener(){

			 @Override
			 public void onClick(View v) {
				 Toast.makeText(NewWeiboActivity.this, "插入话题", Toast.LENGTH_SHORT).show(); 
				String blogContent = etNewBlog.getText().toString();
				NewWeiboActivity.this.etNewBlog.setText(new StringBuffer(blogContent).append("#请插入话题名#").toString());
				blogContent = etNewBlog.getText().toString();
				SpannableString spannableString = new SpannableString(blogContent);
	            ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);   
	            spannableString.setSpan(span, blogContent.length()-9, blogContent.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);   
	            etNewBlog.setText(spannableString);   
			 }
	       });
	

        this.ibInsertAt.setOnClickListener(new ImageButton.OnClickListener(){

 		 @Override
 		 public void onClick(View v) {
 			Toast.makeText(NewWeiboActivity.this, "用户名", Toast.LENGTH_SHORT).show(); 
 			String blogContent = etNewBlog.getText().toString();
 			NewWeiboActivity.this.etNewBlog.setText(new StringBuffer(blogContent).append("#请插入 用户名#").toString());
 			blogContent = etNewBlog.getText().toString();
 			SpannableString spannableString = new SpannableString(blogContent);
             ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);   
             spannableString.setSpan(span, blogContent.length()-8, blogContent.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);   
             etNewBlog.setText(spannableString);   
 		 }
        });
	}
	


	//按下拍照键后，会返回到你的activity，所以你的activity要在onActivityResult方法里加一个处理，
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 
		super.onActivityResult(requestCode, resultCode, data);
		try {
			Bundle extras = data.getExtras();
			Bitmap b = (Bitmap) extras.get("data");
			// 以上两句是固定的写法

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			dat = baos.toByteArray();
			// 将从外部导入饿图片显示到控件Image(id="ivInsertpic")
			ImageView ivInsertpic = (ImageView) findViewById(R.id.ivInsertpic);
			ivInsertpic.setVisibility(View.VISIBLE);
			ivInsertpic.setImageBitmap(b);
			this.hasPic = true;
		} catch (Exception e) {
			this.hasPic = false;
			Toast.makeText(this, "相机连接过程中发生错误", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void refresh(Object... param) {
		if((Integer)param[0] == REF_NEW_WEIBO_RESULT){
			//关闭进度条
			this.progress4NewProgress.setVisibility(View.GONE);
			//发送结果
			String msg = (String) param[1];
			Intent intent = new Intent();
			/* 取得Bundle对象中的数据 */
			Bundle bunde = new Bundle();
			bunde.putString("newBlogResult", msg);
			intent.putExtras(bunde);
			this.setResult(RESULT_OK, intent);
			this.finish();
		}
	}
	
	
   
}
